from logging import getLogger

logging = getLogger(__name__)


def nms_target(rect_grub, rect_target):
    """
    计算两个矩形的重合度（IoU）

    参数:
    rect1, rect2: 每个矩形由四个元素的列表或元组表示 [x_min, y_min, x_max, y_max]

    返回:
    两个矩形的重合度（IoU）
    """
    # 提取坐标
    x1_min, y1_min, x1_max, y1_max = rect_grub
    x2_min, y2_min, x2_max, y2_max = rect_target

    # 计算交集的坐标
    inter_xmin = max(x1_min, x2_min)
    inter_ymin = max(y1_min, y2_min)
    inter_xmax = min(x1_max, x2_max)
    inter_ymax = min(y1_max, y2_max)

    # 计算交集面积
    inter_area = max(0, inter_xmax - inter_xmin) * max(0, inter_ymax - inter_ymin)

    # 计算并集面积
    # area1 = (x1_max - x1_min) * (y1_max - y1_min)
    area2 = (x2_max - x2_min) * (y2_max - y2_min)
    # union_area = area1 + area2 - inter_area

    # 计算重合度（IoU）
    iou = inter_area / area2 if area2 != 0 else 0

    return iou


def get_block_content_bbox(blocks: dict, rect) -> str:
    content = ""
    # max_nms = 0.1
    threshold_nms = 0.6

    for block in blocks:
        block_rect = block[:4]
        currect_nms = nms_target(rect, block_rect)
        if currect_nms > threshold_nms:
            content += block[4]
        if currect_nms > 0.0:
            logging.debug(f"{block_rect} {rect} {currect_nms}")

    return content
